package cn.jy.map.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jy.map.domain.Nurse;
import cn.jy.map.domain.achieve.JCRewardPunishment;
import cn.jy.map.domain.achieve.NurseAchievements;
import cn.jy.map.domain.achieve.NursePostWagesDetail;
import cn.jy.map.domain.achieve.ProvidersCollPNum;
import cn.jy.map.mapper.AchievementsMapper;
import cn.jy.map.mapper.LcblfyMapper;
import cn.jy.map.mapper.VillageColligateMapper;
import cn.jy.map.service.AchievementsService;
import cn.jy.map.utils.GjzType;
import cn.jy.map.utils.MapUtils;
import cn.jy.nvr.datasource.DataSourceConst;
import cn.jy.nvr.datasource.DataSourceContextHolder;

@Service("achievementsService")
public class AchievementsServiceImpl implements AchievementsService {

	@Autowired
	LcblfyMapper lcblfyMapper;
	@Autowired
	AchievementsMapper achievementsMapper;
	@Autowired
	VillageColligateMapper villageColligateMapper;

	Logger logger = Logger.getLogger(AchievementsServiceImpl.class);
	
	
	@Override
	public void loadAchievePostJx(String year, int month) {
		logger.info("构造所有有岗位绩效比例的护士的岗位绩效数据 ");
		
		Map<String, Float> map = MapUtils.getNursePostWagesProportion();
		Set<String> nurseSet = map.keySet();
		
		//采浆室平均绩效 * 岗位绩效比例
		
		if(year == null || "".equals(year)){
			//如果年份为null，默认当前年
			year = MapUtils.getCurrentYear();
		}
		
		boolean isLoadAllMonth = false;//是否构造 year 年的所有月份
		
		if(month < 1 || month > 12){
			//如果月份为超过正常月份的值，则为 year 年的所有月，包含当前时间处在的月
			if(year.equals(MapUtils.getCurrentYear())){
				//如果是当前年，则就看当前月是多少
				month = MapUtils.getCurrentMonth();
			}else{
				month = 12;
			}
			isLoadAllMonth = true;//构造当年的所有月份
		}
		
		Set<String> collNurse = MapUtils.COLLNURSEMAP.keySet();
		
		List<String> list = new ArrayList<String>(collNurse);
		DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
		for(int i = 1; i <= month ; i++){
					
			if(!isLoadAllMonth && i != month){
				continue;
			}
			
			//获取采浆室护士的平均绩效
			float avga = achievementsMapper.getNurseAvgAchievements(list, year,i);
			
			if(nurseSet != null && nurseSet.size()>0){
				for (String nurseId : nurseSet) {
					Float p = map.get(nurseId);
					if(p != null){
						float postWages = avga * p;//有岗位绩效比例的护士的岗位绩效
						NurseAchievements na = new NurseAchievements();
						na.setNurseId(nurseId);
						na.setYear(year);
						na.setMonth(i);
						
						na.setPostWages(postWages);
						
						
						achievementsMapper.updateNursePostAchievements(na);
						
						logger.info("更新护士【"+nurseId+"】【"+year+"年"+i+"月】的岗位绩效信息成功！！");
					}
				}
			}
			
			
			
		}
		
	}
	
	@Override
	public void loadAchievementsData(String year ,int month) {
		
		logger.info("构造所有护士的绩效统计信息开始");
		
		//采浆护士
		Map<String,String> collNurseMap = MapUtils.COLLNURSEMAP;
		DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
		List<Nurse> nList = lcblfyMapper.getNurse();
		
		if(year == null || "".equals(year)){
			//如果年份为null，默认当前年
			year = MapUtils.getCurrentYear();
		}
		
		boolean isLoadAllMonth = false;//是否构造 year 年的所有月份
		
		if(month < 1 || month > 12){
			//如果月份为超过正常月份的值，则为 year 年的所有月，包含当前时间处在的月
			if(year.equals(MapUtils.getCurrentYear())){
				//如果是当前年，则就看当前月是多少
				month = MapUtils.getCurrentMonth();
			}else{
				month = 12;
			}
			isLoadAllMonth = true;//构造当年的所有月份
		}
		
		for(int i = 1; i <= month ; i++){
			
			if(!isLoadAllMonth && i != month){
				continue;
			}
			
			for (Nurse nurse : nList) {
				boolean flag = false;
				if(collNurseMap.get(nurse.getNurseId()) != null){
					flag = true;//表示他是采浆护士
				}
				logger.info("构造护士【"+nurse.getNurseId()+" ："+nurse.getNurseName()+"】【"+year+"年"+i+"月】的绩效统计信息");
				
				
				NurseAchievements na = new NurseAchievements();
				na.setNurseId(nurse.getNurseId());
				na.setNurseName(nurse.getNurseName());
				na.setYear(year);
				na.setMonth(i);
				
				boolean isUpdate = false;//是否更新
				DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
				List<NurseAchievements> naList = achievementsMapper.getNurseAchievements(na);
				if(naList != null && naList.size()>0){
					na = naList.get(0);
					isUpdate = true;
				}
				float baseWages = MapUtils.getNurseBaseWages(nurse.getNurseId());
				na.setBaseWages(baseWages);//基本工资
				
				float postWages = 0;//岗位绩效 = （采浆人数 * 7.5）- 基本工资
				float providerDevWages = 0;//血源发展绩效 = （护士链接的人中的（新浆员 + 复苏浆员）的采浆次数） * 15
				float rewardPunishWages = 0;//奖惩金额
				
				//查询岗位绩效
				if(flag){
					//如果是采浆护士
					DataSourceContextHolder.setDataSourceType(DataSourceConst.jingying);
					String nurseId = nurse.getNurseId().substring(3, nurse.getNurseId().length());
					int nurseCollPNum = achievementsMapper.getNurseCollPNum(nurseId, year+"-"+ i + "-01", MapUtils.getLastDayOfMonth(Integer.parseInt(year), i));
					if(nurseCollPNum > 0){
						postWages = new Float(nurseCollPNum * 7.5) - baseWages;
						if(postWages < 0){
							postWages = 0;
						}
					}
				}else{
					//不是采浆护士：采浆室平均绩效 * 岗位绩效比例
					//非采浆护士的岗位绩效这里不计算，在这个地方把采浆室所有拿出来单独计算，然后后面再汇总计算其他护士的岗位绩效，根据这里的结果
				}
				
				//查询血源发展绩效
				List<String> list1 = this.getNurseCollProvider(nurse.getNurseId(), 2);//复苏浆员
				List<String> list2 = this.getNurseCollProvider(nurse.getNurseId(), 3);//今年新浆员
				if(list1 != null && list2 != null){
					list1.addAll(list2);
				}
				if(list1.size()>0){
					DataSourceContextHolder.setDataSourceType(DataSourceConst.jingying);
					int collNumsByProviders = villageColligateMapper.getCollNumsByProviders( year+"-"+ i + "-01",  MapUtils.getLastDayOfMonth(Integer.parseInt(year), i), list1);
					if(collNumsByProviders > 0){
						providerDevWages = collNumsByProviders * 15;
					}
				}
				
				//获取奖惩金额
				DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
				List<JCRewardPunishment> nurseJc = achievementsMapper.getNurseJc(nurse.getNurseId(), year+"-"+ i + "-01", MapUtils.getLastDayOfMonth(Integer.parseInt(year), i));
				if(nurseJc != null && nurseJc.size()>0){
					for (JCRewardPunishment jc : nurseJc) {
						float sumAfter = jc.getSUMAFTER();
						
						rewardPunishWages += sumAfter;
					}
				}
				
				
				na.setPostWages(postWages);//岗位绩效
				na.setProviderDevWages(providerDevWages);//血源发展绩效
				na.setRewardPunishWages(rewardPunishWages);//奖惩金额
				float shouldWages = baseWages + postWages + providerDevWages;
				na.setShouldWages(shouldWages);//应发工资
				float actualWages = baseWages + postWages + providerDevWages + rewardPunishWages;
				na.setActualWages(actualWages);//实发工资
				DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
				if(isUpdate){
					achievementsMapper.updateNurseAchievements(na);
					logger.info("更新护士【"+nurse.getNurseId()+" ："+nurse.getNurseName()+"】【"+year+"年"+i+"月】的绩效统计信息成功");
				}else{
					na.setId(UUID.randomUUID().toString());
					achievementsMapper.saveNurseAchievements(na);
					logger.info("保存护士【"+nurse.getNurseId()+" ："+nurse.getNurseName()+"】【"+year+"年"+i+"月】的绩效统计信息成功");
				}
				
				
			}
			
		}
		
		
	}
	
	private List<String> getNurseCollProvider(String nurseId,int gjzType){
		//获取护士下面链接的浆员卡号集合
		DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
		List<String> allist = lcblfyMapper.getNurseConnProviderNoList(nurseId,MapUtils.getThatYear(MapUtils.getCurrentYear(), -56));
		List<String> pList = null;
	/*
	 * 1：忠诚浆员，2：服务浆员，3：今年新浆员，4：休眠浆员，5：流失浆员，6：今年进站的被链接了的浆员，
	 * 7：休眠中未链接浆员，8：今年进站的浆员，9：今年未进站的浆员，10：休眠中已链接的浆员
	 */
		switch (gjzType) {
		case 1:
			pList = MapUtils.allTypeGjzMap.get(GjzType.zhongChengGjz);
			break;
		case 2:
			pList = MapUtils.allTypeGjzMap.get(GjzType.fuSuGjz);//gjzAllTypeMapper.getfsJy(date, thisYear, lastYear);
			break;
		case 3:
			pList = MapUtils.allTypeGjzMap.get(GjzType.thisYearCreated);//gjzAllTypeMapper.getNewJy(date, thisYear, lastYear);
			break;
		case 4:
			pList = MapUtils.allTypeGjzMap.get(GjzType.xiuMianGjz);//gjzAllTypeMapper.getXmJy(date, thisYear, lastYear);
			break;
		case 5:
			pList = MapUtils.allTypeGjzMap.get(GjzType.liuShiGjz);//gjzAllTypeMapper.getLsJy(date, thisYear, lastYear);
			break;
		case 6:
			pList = MapUtils.allTypeGjzMap.get(GjzType.xiuMianBeConnect);// gjzAllTypeMapper.getLjJy("1");//休眠中已链接
			break;
		case 7:
			pList = MapUtils.allTypeGjzMap.get(GjzType.notConnect);//gjzAllTypeMapper.getLjJy(null);//未链接
			break;
		case 8:
			pList = MapUtils.allTypeGjzMap.get(GjzType.thisYearComed);//gjzAllTypeMapper.getThisYearComed(date,thisYear,"1");//今年进站的人
			break;
		case 9:
			pList = MapUtils.allTypeGjzMap.get(GjzType.thisYearNotComed);//gjzAllTypeMapper.getThisYearComed(date,thisYear,null);//今年未进站的人
			break;
		case 10:
			pList = MapUtils.allTypeGjzMap.get(GjzType.xiuMianNotConnect);//休眠中未链接
			break;

		default:
			break;
		}
		if(pList != null && pList.size()>0){
			allist = MapUtils.retainList(allist, pList);
		}
		
		return allist;
	}

	@Override
	public List<NurseAchievements> getNurseAchievements(String nurseId, String year) {
		List<NurseAchievements> naList = null;
		if(nurseId != null && !"".equals(nurseId)){
			if(year == null || "".equals(year)){
				year = MapUtils.getCurrentYear();
			}
			
			logger.info("获取护士【"+nurseId+"】【"+year+"】年的综合绩效！！");
			
			NurseAchievements na = new NurseAchievements();
			na.setNurseId(nurseId);
			na.setYear(year);
			DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
			naList = achievementsMapper.getNurseAchievements(na);
			
		}
		
		return naList;
	}

	@Override
	public List<NursePostWagesDetail> getNursePostWagesDetail(String nurseId, String year, int month) {
	
		
		List<NursePostWagesDetail> npwdList = null;
		
		if(nurseId != null && !"".equals(nurseId)){
			if(year == null || "".equals(year)){
				year = MapUtils.getCurrentYear();
			}
			if(month <= 0){
				month = MapUtils.getCurrentMonth();
			}
			String endDate = "";
			if(year.equals(MapUtils.getCurrentYear()) && month == MapUtils.getCurrentMonth()){
				//证明是当前年的当月，就查询当前时间前一天到当月1号的数据
				endDate = MapUtils.getThatDate(MapUtils.getNowOnlyDateFomat1(), -1, Calendar.DATE);
			}else{
				endDate = MapUtils.getLastDayOfMonth(Integer.parseInt(year), month);
			}
			
			logger.info("获取护士【"+nurseId+"】【"+year+"】年【"+month+"】月的岗位绩效！！");
			
			//采浆护士
			if(MapUtils.COLLNURSEMAP.get(nurseId) != null){
				//表示他是采浆护士
				DataSourceContextHolder.setDataSourceType(DataSourceConst.jingying);
				//查精英，需要调整采浆护士ID，去掉mxz
				if(nurseId.startsWith("mxz")){
					nurseId = nurseId.substring(3, nurseId.length());
				}
				npwdList = achievementsMapper.getNurseMonthCollProvider(nurseId, year+"-"+ month + "-01", endDate);
			}
		}
		
		return npwdList;
	}

	@Override
	public List<Map<String, Object>> getXyfz(String nurseId, String year, int month) {
		
		List<Map<String, Object>> mapList = null;
		
		if(nurseId != null && !"".equals(nurseId)){
			if(year == null || "".equals(year)){
				year = MapUtils.getCurrentYear();
			}
			if(month <= 0){
				month = MapUtils.getCurrentMonth();
			}
			mapList = new ArrayList<Map<String ,Object>>();
			logger.info("获取护士【"+nurseId+"】【"+year+"】年【"+month+"】月的血源发展绩效详情！！");
			
			List<String> list1 = this.getNurseCollProvider(nurseId, 2);//复苏浆员
			List<String> list2 = this.getNurseCollProvider(nurseId, 3);//今年新浆员
			
			//获取复苏浆员 year 年 month 月 的采浆次数
			String m = null;
			if(month < 10){
				m = "0" + month;
			}else{
				m = "" + month;
			}
			String startDate = year+"-"+ m + "-01";
			String endDate = MapUtils.getLastDayOfMonth(Integer.parseInt(year), month);
			DataSourceContextHolder.setDataSourceType(DataSourceConst.jingying);
			List<ProvidersCollPNum> l1 = achievementsMapper.getProvidersCollPNum(list1, startDate, endDate);
			List<ProvidersCollPNum> l2 = achievementsMapper.getProvidersCollPNum(list2, startDate, endDate);
			
			Map<String, Integer> nMap1 = new HashMap<String, Integer>();
			Map<String, Integer> nMap2 = new HashMap<String, Integer>();
			
			if(l1 != null && l1.size()>0){
				for (ProvidersCollPNum pcp : l1) {
					nMap1.put(pcp.getCollDate(),pcp.getCountNum());
				}
			}
			if(l2 != null && l2.size()>0){
				for (ProvidersCollPNum pcp : l2) {
					nMap2.put(pcp.getCollDate(),pcp.getCountNum());
				}
			}
			
			
			
			String d = null; 
			for(int i=1;i<32;i++){
				if(i < 10){
					d = "0"+i;
				}else{
					d = ""+i;
				}
				startDate = year+"-"+ m + "-" + d;
				
				Integer num1 = nMap1.get(startDate);
				Integer num2 = nMap2.get(startDate);
				
				if(num1 != null || num2 != null){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("date", startDate);
					map.put("fsp", num1);
					map.put("newP", num2);
					
					mapList.add(map);
					
				}
			}
		}
		return mapList;
	}

	@Override
	public List<JCRewardPunishment> getJCRewardPunishment(String nurseId, String year, int month) {
		
		List<JCRewardPunishment> jcList = null;
		
		if(nurseId != null && !"".equals(nurseId)){
			if(year == null || "".equals(year)){
				year = MapUtils.getCurrentYear();
			}
			if(month <= 0){
				month = MapUtils.getCurrentMonth();
			}
			logger.info("获取护士【"+nurseId+"】【"+year+"】年【"+month+"】月的血源发展绩效详情！！");
			
			String startDate = year+"-"+ month + "-01";
			String endDate = MapUtils.getLastDayOfMonth(Integer.parseInt(year), month);
			DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
			jcList = achievementsMapper.getNurseJc(nurseId, startDate, endDate);
		}
		
		
		return jcList;
	}

	

}
